package com.jhj.service.bm.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.jhj.po.bm.mapper.BmOrderMapper;
import com.jhj.po.bm.model.BmOrder;
import com.jhj.po.bm.model.OrderAttr;
import com.jhj.po.bm.model.OrderContract;
import com.jhj.po.bm.model.Sale;
import com.jhj.po.user.model.AdminRemind;
import com.jhj.vo.bm.ChartSearchVo;
import com.jhj.vo.bm.OrderBaseVo;
import com.jhj.vo.bm.OrderDetailVo;
import com.jhj.vo.bm.OrderListVo;
import com.jhj.vo.bm.OrderSearchVo;
import com.jhj.service.bm.BmOrderService;
import com.jhj.service.bm.OrderAttrService;
import com.jhj.service.bm.OrderContractService;
import com.jhj.service.bm.SaleService;
import com.jhj.service.bm.SaleStatService;
import com.jhj.service.impl.BaseServiceImpl;
import com.jhj.service.user.AdminRemindService;
import com.jhj.utils.BeanUtilsExp;
import com.jhj.utils.Constants;
import com.jhj.utils.SmsUtil;
import com.jhj.utils.StringUtil;
import com.jhj.utils.TimeStampUtil;

@Service
public class BmOrderServiceImpl extends BaseServiceImpl<BmOrder> implements BmOrderService {

	@Autowired
	protected BmOrderMapper orderMapper;

	@Autowired
	private OrderContractService orderContractService;

	@Autowired
	private SaleService saleService;

	@Autowired
	private OrderAttrService orderAttrService;
	
	@Autowired
	private SaleStatService saleStatService;
	
	@Autowired
	AdminRemindService adminRemindService;
		
	@Override
	public OrderListVo getListVo(BmOrder item) {
		OrderListVo vo = new OrderListVo();
		BeanUtilsExp.copyPropertiesIgnoreNull(item, vo);

		Map<String, String> orderStatusMap = Constants.orderStatusMap;
		vo.setOrderStatusName(orderStatusMap.get(String.valueOf(vo.getOrderStatus())));

		Map<String, String> addFromMap = Constants.addFromMap;
		vo.setAddFromName(addFromMap.get(String.valueOf(vo.getAddFrom())));
		vo.setAddTimeStr(TimeStampUtil.timeStampToDateStr(vo.getAddTime().longValue() * 1000));

		if (vo.getSaleId() != null && vo.getSaleId() > 0) {
			Sale s = new Sale();
			s.setSaleId(vo.getSaleId());
			Sale sale = saleService.selectOne(s);
			if (sale != null) {
				vo.setSaleName(sale.getName());
				vo.setSaleMobile(sale.getMobile());
			}
		}
		
		if (vo.getOrderId() != null && vo.getOrderId() > 0) {
			OrderContract oc = new OrderContract();
			oc.setOrderId(vo.getOrderId());
			oc.setStatus(1);
			OrderContract orderContract = orderContractService.selectOne(oc);
			if (orderContract != null) {
				vo.setOrderPay(orderContract.getOrderPay());
			}
		}
		
		//订单的下单派单情况
		String orderDispatchName = "";
		if (vo.getOrderDispatch() == 0) orderDispatchName = "系统派单";
		if (vo.getOrderDispatch() == 1) orderDispatchName = "自主开发";
		vo.setOrderDispatchName(orderDispatchName);
		
		//工作内容
		String workContent = "";
		OrderAttr searchVo = new OrderAttr();
		searchVo.setOrderId(vo.getOrderId());
		searchVo.setServiceTypeId(vo.getServiceTypeId());
		searchVo.setAttrType("workContent");
		OrderAttr record = orderAttrService.selectOne(searchVo);
	   if (record != null) workContent = record.getAttrValue();
		vo.setWorkContent(workContent);
		 if (record == null) {
		searchVo = new OrderAttr();
		searchVo.setOrderId(vo.getOrderId());
		searchVo.setServiceTypeId(vo.getServiceTypeId());
        List<OrderAttr> list = orderAttrService.selectBySearchVo(searchVo, "");
		for (int i =0;i<list.size();i++) {
			String  value=list.get(i).getAttrValue();
			if(list.get(i).getAttrType().equals("workHomeSquare")) {
					workContent+=list.get(i).getAttrName()+":"+value+"\n";
			}
			if(list.get(i).getAttrType().equals("isChildren")||list.get(i).getAttrType().equals("isOldMan")) {
			    if(list.get(i).getAttrValue().equals("1")) {
				
					workContent+=list.get(i).getAttrName()+":"+"是"+"\n";
				}
				if(list.get(i).getAttrValue().equals("0")) {
					workContent+=list.get(i).getAttrName()+":"+"否"+"\n";
				}
			}
			if(list.get(i).getAttrType().equals("isRest")) {
				 if(list.get(i).getAttrValue().equals("1")) {
					workContent+=list.get(i).getAttrName()+":"+"双休"+"\n";
				}
				if(list.get(i).getAttrValue().equals("0")) {
					
					workContent+=list.get(i).getAttrName()+":"+"单休"+"\n";
				}
			}
		}
		 Integer workHome= item.getWorkHome();
		   if(workHome==1) {
				workContent+="是否住家"+":"+"住家"+"\n";
			}
			if(workHome==0) {
				workContent+="是否住家"+":"+"不住家"+"\n";
			}
	     vo.setWorkContent(workContent);
		 }
		//服务城市区县
		String addr = "";
		searchVo = new OrderAttr();
		searchVo.setOrderId(vo.getOrderId());
		searchVo.setServiceTypeId(vo.getServiceTypeId());
		searchVo.setAttrType("addr");
		record = orderAttrService.selectOne(searchVo);
		if (record != null) addr = record.getAttrValue();
		vo.setAddr(addr);
		
		//薪水
		String salary = "";
		searchVo = new OrderAttr();
		searchVo.setOrderId(vo.getOrderId());
		searchVo.setServiceTypeId(vo.getServiceTypeId());
		searchVo.setAttrType("salary");
		record = orderAttrService.selectOne(searchVo);
		if (record != null) salary = record.getAttrValue();
		vo.setSalary(salary);
		
		return vo;
	}
	
	@Override
	public OrderDetailVo getDetailVo(BmOrder item) {
		OrderDetailVo vo = new OrderDetailVo();
		OrderListVo listVo = this.getListVo(item);
		BeanUtilsExp.copyPropertiesIgnoreNull(listVo, vo);
		
		//服务地址
		String serviceAddr = "";
		OrderAttr searchVo = new OrderAttr();
		searchVo.setOrderId(vo.getOrderId());
		searchVo.setServiceTypeId(vo.getServiceTypeId());
		searchVo.setAttrType("serviceAddr");
		OrderAttr record = orderAttrService.selectOne(searchVo);
		if (record != null) serviceAddr = record.getAttrValue();
		vo.setServiceAddr(serviceAddr);
		
		
		//详细内容
		String workContentAddon = "";
		searchVo = new OrderAttr();
		searchVo.setOrderId(vo.getOrderId());
		searchVo.setServiceTypeId(vo.getServiceTypeId());
		searchVo.setAttrType("workContentAddon");
		record = orderAttrService.selectOne(searchVo);
		if (record != null) {
		workContentAddon = record.getAttrValue();
		vo.setWorkContentAddon(workContentAddon);
		}
		if(record==null){
		searchVo = new OrderAttr();
		searchVo.setOrderId(vo.getOrderId());
		searchVo.setServiceTypeId(vo.getServiceTypeId());
        List<OrderAttr> list = orderAttrService.selectBySearchVo(searchVo, "");
		for (int i =0;i<list.size();i++) {
			    String  value=list.get(i).getAttrValue();
			    if(list.get(i).getAttrType().equals("workHomeSquare")) {
				    workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
				}
				if(list.get(i).getAttrType().equals("Population")) {
					 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
			    }
				if(list.get(i).getAttrType().equals("longTime")) {
					 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
			    }
				if(list.get(i).getAttrType().equals("workTime")) {
					 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
			    }
				if(list.get(i).getAttrType().equals("isChildren")||list.get(i).getAttrType().equals("isOldMan")||list.get(i).getAttrType().equals("isHealth")||list.get(i).getAttrType().equals("isLookAfterOldman")) {
				    if(list.get(i).getAttrValue().equals("1")) {
						value="是";
						workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
					}
					if(list.get(i).getAttrValue().equals("0")) {
						value="否";
						 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
					}
				}
				if(list.get(i).getAttrType().equals("childrenAge")) {
					 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
			    }
				if(list.get(i).getAttrType().equals("oldManAge")) {
					 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
			    }
				if(list.get(i).getAttrType().equals("classes")) {
					 if(list.get(i).getAttrValue().equals("1")) {
							value="钟点工";
							 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
					}
					if(list.get(i).getAttrValue().equals("0")) {
							value="白班";
							 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
					}
					if(list.get(i).getAttrValue().equals("2")) {
						value="住家";
						 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
				    }
				}
				if(list.get(i).getAttrType().equals("isRest")) {
					 if(list.get(i).getAttrValue().equals("1")) {
							value="双休";
							 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
					}
					if(list.get(i).getAttrValue().equals("0")) {
							value="单休";
							 workContentAddon+=list.get(i).getAttrName()+":"+value+"\n";
					}
				}
		}
		   }
		vo.setWorkContentAddon(workContentAddon);
		
		
		
		
		return vo;
	}

	/**
	 * 订单最基础的信息接口（简化的订单订单详情）
	 */
	@Override
	public OrderBaseVo getBaseInfo(BmOrder order) {
		OrderBaseVo vo = new OrderBaseVo();
		BeanUtilsExp.copyPropertiesIgnoreNull(order, vo);

		Map<String, String> orderStatusMap = Constants.orderStatusMap;
		vo.setOrderStatusName(orderStatusMap.get(String.valueOf(order.getOrderStatus())));

		vo.setAddTimeStr(TimeStampUtil.timeStampToDateStr(order.getAddTime().longValue() * 1000));

		return vo;
	}

	@Override
	public List<BmOrder> selectBySearchVo(OrderSearchVo orderVo, String orderBy) {
		
		// 排序
		if (!StringUtil.isEmpty(orderBy)) {
			orderVo.setOrderBy(orderBy);
		}
		
		return orderMapper.selectBySearchVo(orderVo);
	}
	
	@Override
	public List<BmOrder> selectByListPage(OrderSearchVo orderVo, Integer pageNum, Integer pageSize,
			String orderBy) {
		PageHelper.startPage(pageNum, pageSize);

		// 排序
		if (!StringUtil.isEmpty(orderBy)) {
			orderVo.setOrderBy(orderBy);
		}
		
		return orderMapper.selectByListPage(orderVo);
	}
	
	@Override
	public List<Map<String, String>> countOrderNumGbServiceType(ChartSearchVo vo) {

		return orderMapper.countOrderNumGbServiceType(vo);
	}

	/**
	 * 订单统计，按照销售老师统计
	 * 
	 * @param searchVo
	 * @return total : 总订单数 totalProcess : 正在进行的订单数 totalDone : 已签约订单数
	 */
	@Override
	public List<Map<Integer, Integer>> countOrderSale(OrderSearchVo searchVo) {
		return orderMapper.countOrderSale(searchVo);
	}

	/**
	 * 订单统计，反正统计数字
	 */
	@Override
	public int countOrderBySearchVo(ChartSearchVo searchVo) {
		return orderMapper.countOrderBySearchVo(searchVo);
	}
	
	/**
	 * 订单用户统计
	 */
	@Override
	public int statUserNum(ChartSearchVo searchVo) {
		return orderMapper.statUserNum(searchVo);
	}
	

	/**
	 * 订单派工成功的处理方法
	 * @param order				order订单对象
	 * @param dispatchInfo		派工信息，格式为
	 *                           orderDispatch  0 = 系统派单  1 = 自主开发
	 *                           dispatchBy     派工依据
	 *                           saleId		   派工的saleId
	 * @param isSelfDispatch
	 */
	@Override
	public void orderDispatchSuccess(BmOrder order, HashMap<String, Object> dispatchInfo, Boolean isSelfDispatch) {
		
		Integer orderId = order.getOrderId();
		String orderNo = order.getOrderNo();
		Integer dispatchSaleId = Integer.valueOf(dispatchInfo.get("saleId").toString());
		String dispatchBy = dispatchInfo.get("dispatchBy").toString();
		Integer orderDispatch = Integer.valueOf(dispatchInfo.get("orderDispatch").toString());
		Sale sale = saleService.selectByPrimaryKey(dispatchSaleId);

		BmOrder o = new BmOrder();
		o.setOrderId(order.getOrderId());
		o.setSaleId(dispatchSaleId);
		o.setOrderDispatch(orderDispatch);
		o.setOrderDispatchBy(dispatchBy);
		
		//如果是自主下单，则直接变成已接单.
//		if (isSelfDispatch == true) {
			o.setOrderDispatchStatus(1);
//		}
		
		this.update(o);

		
		//讲saleStat先都配置为0，然后再配置派工的老师为1;
		if (isSelfDispatch == false) {
			saleStatService.setDispatchStatus(dispatchSaleId);
		}
		
		String saleMobile = sale.getMobile();
		// 短信提醒销售老师
		// 【叮当到家】系统后台给您派发一条新订单，请抓紧打开后台，及时与客户取得联系

		String[] content = new String[] { "" };
		SmsUtil.SendSms(saleMobile, "243124", content);
		
		//创建管理员提醒信息
		//首先先查询是否已经存在，避免重复的情况
		String remindType = "bm";
		String remindRemark = "你有新的订单需要跟进";
		
		AdminRemind searchVo = new AdminRemind();
		searchVo.setAdminId(dispatchSaleId);
		searchVo.setRemindType(remindType);
		searchVo.setLinkId(orderId);
		searchVo.setLinkNo(orderNo);
		AdminRemind adminRemind = adminRemindService.selectOne(searchVo);
		
		if (adminRemind == null) {
			adminRemind = adminRemindService.initPo(new AdminRemind());
			adminRemind.setRemindType(remindType);
			adminRemind.setRemidLevel(9);
			adminRemind.setAdminId(dispatchSaleId);
			adminRemind.setLinkId(orderId);
			adminRemind.setLinkNo(orderNo);
			adminRemind.setRemark(remindRemark);
			adminRemind.setSendSms(0);
			adminRemind.setSendWx(0);
			adminRemind.setStatus(Constants.ADMIN_REMIND_STATUS_0);
			adminRemind.setAddTime(TimeStampUtil.getNowSecond().intValue());
			adminRemind.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
			adminRemindService.insert(adminRemind);
		}
	}
}
